import React from 'react';
import { connect } from 'react-redux';
import './comm.css';
import axios from 'axios';
import cookie from 'react-cookies';
import { page_query_action } from '../actions/pages';
import { withRouter } from 'react-router-dom';

class MenuBody extends React.Component {
    state = {
        error: ""
    }
    handleClick = (curPage) => {
        let userName = cookie.load('login-name');
        let loginID = cookie.load('login-id');
        axios.post("/app/pageQuery", {
            "userName": userName,
            "curPage": curPage,
            "loginID": loginID
        }).then((res) => {
            if("请先登录" === res.data.errorInfo) {
                this.props.history.push('/login');
            } else {
                this.props.pageQueryAction(res.data);
                if(0 === this.props.loginInfo.subPage.length) {
                    this.props.history.push("/" + curPage);
                }
            }
        }).catch((err) => {
            this.setState({error: "请求服务器端时产生的错误信息: " + err})
        })
    }
    render() {
        let sbp = this.props.loginInfo.subPage;
        const menuHead = undefined === sbp || null === sbp || '' === sbp || 0 === sbp.length ? (
            <div><font color='red'>{this.state.error}</font></div>
        ) : (
            sbp.map(subpg => {
                return (
                    <div className='subDir' key={subpg.page_path}>
                        <img onClick={() => this.handleClick(subpg.page_path)} src={require('../../img/' + subpg.page_path + '.png')} alt={subpg.page_name} heigt='75' width='75' />
                        <br/>
                        <font size='2'>{subpg.page_name}</font>
                    </div>
                )
            })
        )
        return (
            <div align="center">{menuHead}</div>
        )
    }
}

const mapStateToProps = (state) => {
    return state;
}

const mapDispatchToProps = (dispatch) => {
    return {
        pageQueryAction: (loginInfo) => { dispatch(page_query_action(loginInfo)) }
    }
};

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MenuBody));
